package com.cn.wanxi.servlet.back.news;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.NewsModel;
import com.cn.wanxi.service.INewsService;
import com.cn.wanxi.service.impl.NewsServiceImpl;
import com.cn.wanxi.util.DataEncoding;
import com.cn.wanxi.util.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/back/news/info")
public class NewsInfoServlet extends HttpServlet {
    INewsService newsService = new NewsServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DataEncoding.setJsonContentType(resp);
        DataEncoding.setCharacterEncoding(req,resp);
        //新闻详情
        String nid = req.getParameter("id");
        int id = Integer.parseInt(nid);
        NewsModel newsModel = newsService.getNews(id);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("news",newsModel);
        resp.getWriter().print(jsonObject);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DataEncoding.setJsonContentType(resp);
        DataEncoding.setCharacterEncoding(req,resp);
        //新闻模糊查询
        String title = req.getParameter("title");
        String news_type = req.getParameter("news_type");
        String start_date = req.getParameter("start_date");
        String end_date = req.getParameter("end_date");
        String pageSize = req.getParameter("page");
        String pageNum = req.getParameter("size");
        int page = Integer.parseInt(pageSize);
        int size = Integer.parseInt(pageNum);
        //SQL语句拼接
        String sql = "select * from news where 1=1 ";
        if (!"".equals(title))
            sql+="and title='"+title+"'";
        if (!news_type.equals("全部"))
            sql+="and news_type='"+news_type+"'";
        if (!"".equals(start_date))
            sql+="and date>='"+start_date+"'";
        if (!"".equals(end_date))
            sql+="and date<='"+end_date+"'";
        long total = JDBCUtils.getCount(sql.replace("*","count(*)"));
        sql+=" limit "+ (page-1)*size +","+size;
        List<NewsModel> list = newsService.searchNews(sql);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("news",list);
        jsonObject.put("total",total);
        resp.getWriter().print(jsonObject);
    }
}
